﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using MediaArtAggregator.Core.Configuration;

namespace MediaArtAggregator.Core.SearchProvider {
  public class YahooSearchSource : ApiBasedSearchSource {
    public override string ToString ( ) {
      return "images.yahoo.com";
    }

    public override void Search ( string search, Settings settings, SearchType searchType ) {
      this.OnSearchInitialize ( EventArgs.Empty );
      string appid = "cqPDwOzV34EqvNJt56.9g2Jmd2ru72B1LKCBixoYArKuL6m513noIYTprwiXLl4RRQ--";
      string searchUrl = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid={0}&query={1}+{2}&results=50&adult_ok=1";

      XDocument doc = XDocument.Load ( string.Format ( searchUrl, appid, Utilities.GetSafeSearchString (search), 
        string.IsNullOrEmpty(searchType.Value) ? string.Empty : Utilities.GetSafeSearchString (searchType.Value) ) );
      var images = from c in doc.Descendants ( XName.Get ( "Result", "urn:yahoo:srchmi" ) )
                   where !string.IsNullOrEmpty ( ( string ) c.Element ( XName.Get ( "Url", "urn:yahoo:srchmi" ) ) )
                   select new Uri ( ( string ) c.Element ( XName.Get ( "Url", "urn:yahoo:srchmi" ) ) );
      foreach ( Uri u in images ) {
        this.Results.Add ( u );
      }
      this.OnSearchComplete ( EventArgs.Empty );
    }
  }
}
